package com.caigou.modules.service.ui

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.caigou.comm.base.bean.AppBackgroundInfo
import com.caigou.comm.base.container.BaseFragment
import com.caigou.comm.base.ext.Resource
import com.caigou.comm.base.ext.observe
import com.caigou.comm.base.ext.showToast
import com.caigou.comm.base.widget.SpaceItemDecoration
import com.caigou.modules.service.R
import com.caigou.modules.service.adapter.WebsiteCollectItemAdapter
import com.caigou.modules.service.baen.WebsiteCollectBean
import com.caigou.modules.service.baen.WebsiteCollectItemBean
import com.caigou.modules.service.databinding.FragmentWebsiteCollectBinding
import com.caigou.modules.service.viewmodel.ServiceViewModel
import com.caigou.modules.service.widget.WebsiteCollectDialog
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author #Suyghur.
 * Created on 2021/11/11
 */
@AndroidEntryPoint
class WebsiteCollectFragment : BaseFragment() {

    private var _binding: FragmentWebsiteCollectBinding? = null
    private val binding get() = _binding!!

    private val serviceViewModel: ServiceViewModel by viewModels()

    private var page: Long = 1L
    private val limit: Long = 10L
    private var totalPage = 0

    private val itemCallback = object : WebsiteCollectItemAdapter.IItemCallback {
        override fun onEnter(item: WebsiteCollectItemBean) {
            openBrowser(item.url)
        }

        override fun onDelete(item: WebsiteCollectItemBean) {
            serviceViewModel.deleteWebsiteCollect(AppBackgroundInfo.instance.userBean!!.userId, item.id)
        }
    }

    private val linearLayoutManager: LinearLayoutManager by lazy {
        LinearLayoutManager(requireActivity())
    }

    private val mAdapter: WebsiteCollectItemAdapter by lazy {
        WebsiteCollectItemAdapter(mutableListOf(), itemCallback)
    }

    private val recyclerViewItemDecoration by lazy {
        SpaceItemDecoration(requireActivity())
    }

    private var collectDialog: WebsiteCollectDialog? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        _binding = FragmentWebsiteCollectBinding.inflate(inflater, container, false)
        return _binding?.root
    }

    override fun initView() {
        binding.websiteCollectSwipeRefreshLayout.run {
            setColorSchemeColors(resources.getColor(R.color.caigou_theme_color))
            setOnRefreshListener {
                mAdapter.loadMoreModule.isEnableLoadMore = false
                page = 1L
                serviceViewModel.getWebsiteCollectList(page, limit, AppBackgroundInfo.instance.userBean!!.userId)
            }
        }

        mAdapter.loadMoreModule.run {
            setOnLoadMoreListener {
                mAdapter.loadMoreModule.isEnableLoadMore = true
                serviceViewModel.getWebsiteCollectList(page, limit, AppBackgroundInfo.instance.userBean!!.userId)
            }
            isAutoLoadMore = true
            isEnableLoadMoreIfNotFullPage = false
        }

        binding.websiteCollectRecyclerView.run {
            layoutManager = linearLayoutManager
            adapter = mAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(recyclerViewItemDecoration)
        }

        binding.websiteCollectTvAdd.setOnClickListener {
            collectDialog?.apply {
                dismiss()
                collectDialog = null
            }
            collectDialog = WebsiteCollectDialog(requireActivity())
            collectDialog?.run {
                btnCancel.setOnClickListener {
                    collectDialog?.apply {
                        dismiss()
                        collectDialog = null
                    }
                }
                btnConfirm.setOnClickListener {
                    val url = etUrl.text.toString()
                    val desc = etDesc.text.toString()
                    serviceViewModel.addWebsiteCollect(AppBackgroundInfo.instance.userBean!!.userId, desc, url)
                    dismiss()
                    collectDialog = null
                }
                show()
            }
        }

        binding.websiteCollectTvBack.setOnClickListener {
            (requireActivity() as ServiceActivity).onBackPressed()
        }
    }

    override fun lazyLoad() {
        serviceViewModel.getWebsiteCollectList(page, limit, AppBackgroundInfo.instance.userBean!!.userId)
    }

    override fun onBack() {
    }

    override fun observeViewModel() {
        super.observeViewModel()
        observe(serviceViewModel.websiteCollectListLiveData, ::handleGetWebsiteCollectList)
        observe(serviceViewModel.websiteCollectDeleteLiveData, ::handleDeleteWebsiteCollect)
        observe(serviceViewModel.websiteCollectAddLiveData, ::handleAddWebsiteCollect)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    private fun handleGetWebsiteCollectList(result: Resource<WebsiteCollectBean>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.websiteCollectSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取收藏网址信息异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.websiteCollectSwipeRefreshLayout.isRefreshing = false
                mAdapter.loadMoreModule.isEnableLoadMore = true

                if (result.data == null) {
                    return
                }
                totalPage = result.data!!.totalPage

                if (page == 1L) {
                    mAdapter.setList(result.data!!.list)
                } else {
                    mAdapter.addData(result.data!!.list)
                }

                if (result.data!!.pageSize < limit) {
                    mAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    mAdapter.loadMoreModule.loadMoreComplete()
                }

                if (page >= totalPage) {
                    mAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    page++
                }
            }
        }
    }

    private fun handleDeleteWebsiteCollect(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("删除收藏网址异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()

                if (result.data == null) {
                    return
                }
                page = 1L
                totalPage = 0
                serviceViewModel.getWebsiteCollectList(page, limit, AppBackgroundInfo.instance.userBean!!.userId)
            }
        }
    }

    private fun handleAddWebsiteCollect(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("添加收藏网址异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()

                if (result.data == null) {
                    return
                }
                page = 1L
                totalPage = 0
                serviceViewModel.getWebsiteCollectList(page, limit, AppBackgroundInfo.instance.userBean!!.userId)
            }
        }
    }

    private fun openBrowser(url: String) {
        if (url.startsWith("https://") || url.startsWith("http://")) {
            startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
        } else {
            startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://${url}")).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
        }
    }
}